package com.example.kevin.controller;

import com.alibaba.fastjson2.JSON;
import com.example.kevin.entity.Task;
import com.example.kevin.resp.Resp;
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.Table;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;

/**
 * Author: Kevin
 * Date: 2023/5/3 15:38
 */
@Slf4j
@RestController
public class TestGuavaController {
    @PostMapping("testTable")
    public Resp testTable() {
        Table<String, String, String> table = HashBasedTable.create();
        table.put("IBM", "101", "Mahesh");
        table.put("IBM", "102", "Ramesh");
        table.put("IBM", "103", "Suresh");

        table.put("Microsoft", "111", "Sohan");
        table.put("Microsoft", "112", "Mohan");
        table.put("Microsoft", "113", "Rohan");

        table.put("TCS", "121", "Ram");
        table.put("TCS", "122", "Shyam");
        table.put("TCS", "123", "Sunil");
        table.put("TCS", "1234", "Sunil4");
        Map map = ((HashBasedTable) table).rowMap();
        log.info(JSON.toJSONString(map));
        return Resp.succ(map);
    }

    @PostMapping("testCountDownLatch")
    public Resp testCountDownLatch() {
        final boolean[] callbackRan = {false};
        CountDownLatch startSignal = new CountDownLatch(2);
        ListeningExecutorService service = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(10));
        ListenableFuture<String> futureTask = service.submit(new Task(startSignal));
        futureTask.addListener(() -> {
            callbackRan[0] = false;
            log.info("{}, {}", Thread.currentThread().getId(), Thread.currentThread().getName());
        }, service);
        return Resp.succ();
    }
}
